package com.zaofan.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zaofan.bean.AdImg;
import com.zaofan.bean.Admin;
import com.zaofan.bean.Product;
import com.zaofan.bean.Shop;
import com.zaofan.service.AdImgService;
import com.zaofan.service.ProductService;
import com.zaofan.service.ShopService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

@WebServlet("/banner")
public class AdImgController extends BaseServlet {
	private static final long serialVersionUID = -5377620282223515871L;
	private AdImgService adImgService = new AdImgService();
	private ProductService productService = new ProductService();
	private ShopService shopService = new ShopService();

	protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			List<AdImg> adImgs = adImgService.findAll(params);
			Long count = adImgService.count(params);
			JsonUtils.writeSuccessPageJson("查询成功", adImgs, count, response);

		} catch (Exception e) {
			JsonUtils.writeFailJson("参数错误!!", response);
		}
		JsonUtils.writeFailJson("查询失败!!", response);
	}

	protected void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String temp = request.getParameter("id");
		try {
			Long id = Long.valueOf(temp);
			AdImg adImg = adImgService.findById(id);
			JsonUtils.writeSuccessJson("查询成功", adImg, response);
		} catch (Exception e) {
			JsonUtils.writeFailJson("参数错误!!", response);
		}
		JsonUtils.writeFailJson("查询失败!!", response);
	}

	protected void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			AdImg adImg = WebUtils.write2bean(request, AdImg.class);
			adImgService.delete(adImg);
			JsonUtils.writeSuccessJson("删除成功", "", response);
		} catch (Exception e) {
			JsonUtils.writeFailJson("参数错误!!", response);
		}
		JsonUtils.writeFailJson("删除失败!!", response);
	}

	protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			AdImg adImg = null;
			Result result = fileUploadHanderAdImg(request);
			if(result == null){
				JsonUtils.writeFailJson("添加失败!!", response);
				return;
			}
			adImg = result.adImg;
			if ("ad".equals(adImg.getTypeLable())) {


				adImg.setLinkUrl(result.attribute);
			} else if ("adproduct".equals(adImg.getTypeLable())) {
				int productId = Integer.valueOf(result.attribute);
				Product product = productService.findById(productId);
				if(product == null){
					JsonUtils.writeFailJson("产品不存在!!", response);
					return;
				}
				adImg.setLinkId(productId);
			} else if ("adpage".equals(adImg.getTypeLable())) {
				adImg.setPageCode(result.attribute);
			}else if("adshop".equals(adImg.getTypeLable())){
				int shopId = Integer.valueOf(result.attribute);
				Shop shop = shopService.findById(shopId);
				if(shop == null){
					JsonUtils.writeFailJson("商铺不存在!!", response);
					return;
				}
				adImg.setLinkId(shopId);
			}
			adImgService.add(adImg);
			JsonUtils.writeSuccessJson("添加成功!!", "", response);
		} catch (Exception e) {
			JsonUtils.writeFailJson("属性错误!!", response);
		}
	}

	protected void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			AdImg adImg = null;
			Result result = null;
			String attribute = "";
			if (isMultipart) {
				result = fileUploadHanderAdImg(request);
				adImg = result.adImg;
				attribute = result.attribute;
			} else {
				adImg = WebUtils.write2bean(request, AdImg.class);
				attribute =  request.getParameter("attribute");
			}
			if ("ad".equals(adImg.getTypeLable())) {
				adImg.setLinkUrl(attribute);
			} else if ("adproduct".equals(adImg.getTypeLable())) {
				adImg.setLinkId(Integer.valueOf(attribute));
			} else if ("adpage".equals(adImg.getTypeLable())) {
				adImg.setPageCode(attribute);
			}else if("adshop".equals(adImg.getTypeLable())){
				int shopId = Integer.valueOf(result.attribute);
				Shop shop = shopService.findById(shopId);
				if(shop == null){
					JsonUtils.writeFailJson("商铺不存在!!", response);
					return;
				}
				adImg.setLinkId(shopId);
			}
			adImgService.update(adImg);
			JsonUtils.writeSuccessJson("更新成功!!", "", response);
		} catch (Exception e) {
			JsonUtils.writeFailJson("更新失败!!", response);
		}
	}

	protected void state(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String temp = request.getParameter("id");
		try {
			Long id = Long.valueOf(temp);
			AdImg adImg = adImgService.findById(id);
			adImg.setState(adImg.getState() == 0 ? 1 : 0);
			adImgService.update(adImg);
			JsonUtils.writeSuccessJson("更新成功!!", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("参数错误!!", response);
		}
		JsonUtils.writeFailJson("更新失败!!", response);
	}

	private Result fileUploadHanderAdImg(HttpServletRequest request) {
		AdImg adImg = new AdImg();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String random = new Random().nextInt() + "";
		String attribute = "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {

				if (item.isFormField()) {
					String value = new String(item.getString().getBytes("ISO8859-1"), "UTF-8");
					String key = item.getFieldName();
					if("attribute".equals(key)){
						attribute = value;
						continue;
					}
					BeanUtils.setProperty(adImg, key, value);
					System.out.println(key + " = " + value);
				} else {
//					if(item.getFieldName().equals("picture")){
//
//					}

					InputStream in = item.getInputStream();
					String path = WebUtils.makeDir(this.getServletContext().getRealPath("/ad_img"), random + "") + "/"
							+ WebUtils.getUUID() + "_" + random
							+ item.getName().substring(item.getName().lastIndexOf("."));
					FileOutputStream out = new FileOutputStream(
							this.getServletContext().getRealPath("/ad_img") + "/" + path);

					BufferedOutputStream bos = new BufferedOutputStream(out);

					int len = 0;
					byte[] buff = new byte[1024];
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					adImg.setPicture("/ad_img/" + path);

//					if(item.getFieldName().equals("htmlpic")){
						//写文件 html 图片
						//存入数据库属性
//						attribute = "url"

//					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Result result = new Result();
		result.adImg = adImg;
		result.attribute = attribute;
		return result;
	}


}

class Result{
	AdImg adImg;
	String attribute;
}
